package com.saas.platform.demo.base.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

/**
 * 检查每个接口的返回时间
 *
 */
public class AccessLogInterceptor extends HandlerInterceptorAdapter {

	Logger logger = LoggerFactory.getLogger(AccessLogInterceptor.class);
	

	private static ThreadLocal<Long> apiTimer = new ThreadLocal<>();

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		try {
			apiTimer.set(System.currentTimeMillis());
            String uri = request.getRequestURI();
            String method = request.getMethod();
            logger.debug(">>>>>>>>>>>接口请求开始, uri:{}, method:{}", uri, method);
        } catch (Exception ex) {
            logger.error("接口请求日志拦截器错误[begin]:", ex);
        }
		return true;
	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		try{
			long beginTime = apiTimer.get();
			long endTime = System.currentTimeMillis();
			apiTimer.remove();
			String uri = request.getRequestURI();
			logger.debug(">>>>>>>>>>接口请求结束, uri:{}, total time:{} ms", uri, (endTime - beginTime));
		}catch (Exception e) {
            logger.error("接口请求日志拦截器错误[end]:", e);
        }

	}

	
	
}
